/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.user.client.ui;

import java.text.ParseException;

import com.cleangwt.uibinder.client.TemplateSupport;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.text.client.DoubleParser;
import com.google.gwt.text.shared.AbstractRenderer;
import com.google.gwt.text.shared.Parser;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.ValueBoxBase;

/**
 * A number input box.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public class NumberBox extends ValueBoxBase<Number> {
  public static final String DATA_FORMAT = "data-format";

  public static class NumberParser implements Parser<Number> {
    private static NumberParser INSTANCE;

    /**
     * Returns the instance of the no-op renderer.
     */
    public static Parser<Number> instance() {
      if (INSTANCE == null) {
        INSTANCE = new NumberParser();
      }
      return INSTANCE;
    }

    protected NumberParser() {
    }

    @Override
    public Number parse(CharSequence object) throws ParseException {
      return DoubleParser.instance().parse(object);
    }
  }

  public static class NumberRenderer extends AbstractRenderer<Number> {
    public static final String DEFULT_PATTERN = "#,##0";
    private final String format;

    public static String getDefaultPattern(int scale) {
      StringBuilder sb = new StringBuilder(DEFULT_PATTERN);
      if (scale > 0) {
        sb.append(".");
        for (int i = 0; i < scale; i++) {
          sb.append("#");
        }
      }
      return sb.toString();
    }

    public NumberRenderer(String format) {
      assert format != null : "You may not specify a null format.";
      this.format = format;
    }

    @Override
    public String render(Number value) {
      if (value == null) {
        return "";
      }
      return NumberFormat.getFormat(format).format(value);
    }

  }

  public static final String DEFAULT_STYLENAME = "gwt-NumberBox";

  /**
   * Creates a nubmer box that wraps an existing &lt;input&gt; element of template.
   * 
   * @param template the template
   * @param element the element to be wrapped
   */
  public static NumberBox wrap(TemplateSupport template, Element element) {
    NumberBox widget = new NumberBox(element);
    template.wrap(widget);
    return widget;
  }

  /**
   * Creates a number box with the default scale '0' for integer inputs.
   */
  public NumberBox() {
    this(NumberRenderer.DEFULT_PATTERN);
  }

  private static Element createInputElement(String format) {
    Element e = Document.get().createTextInputElement();
    e.setAttribute(DATA_FORMAT, format);
    return e;
  }

  /**
   * Creates a number box with the specified scale for float-number inputs.
   * 
   * @param scale the scale of float points
   */
  public NumberBox(int scale) {
    this(NumberRenderer.getDefaultPattern(scale));
  }

  /**
   * Creates a number box with the given number format.
   * 
   * @param format the number format
   */
  public NumberBox(String format) {
    this(createInputElement(format));
    setStyleName(DEFAULT_STYLENAME);
  }

  /**
   * This constructor may be used by subclasses to explicitly use an existing element. This element
   * must be a &lt;div&gt; element.
   * 
   * @param element the element to be used
   * @param renderer the number renderer
   */
  protected NumberBox(Element element) {
    super(element, new NumberRenderer(DATA_FORMAT), NumberParser.instance());
    setAlignment(TextAlignment.RIGHT);
    this.sinkEvents(Event.ONCHANGE | Event.ONFOCUS | Event.ONBLUR);
  }

  /**
   * This constructor may be used by subclasses to explicitly use an existing element. This element
   * must be a &lt;div&gt; element.
   * 
   * @param element the element to be used
   * @param renderer the number renderer
   */
  protected NumberBox(Element element, NumberRenderer renderer) {
    super(element, renderer, NumberParser.instance());
    setAlignment(TextAlignment.RIGHT);
    this.sinkEvents(Event.ONCHANGE | Event.ONFOCUS | Event.ONBLUR);
  }

  // /**
  // * Retrieves an integer value.
  // *
  // * @return the integer value
  // */
  // public Integer getIntValue() {
  // Number value = getValue();
  // if (value == null) {
  // return null;
  // } else {
  // return value.intValue();
  // }
  // }
  //
  // /**
  // * Retrieves an long value.
  // *
  // * @return the long value
  // */
  // public Long getLongValue() {
  // Number value = getValue();
  // if (value == null) {
  // return null;
  // } else {
  // return value.longValue();
  // }
  // }

  @Override
  public void onBrowserEvent(Event event) {
    int type = DOM.eventGetType(event);
    if (type == Event.ONCHANGE) {
      setValue(getValue());
    } else if (type == Event.ONFOCUS) {
      setAlignment(TextAlignment.LEFT);
    } else if (type == Event.ONBLUR) {
      setAlignment(TextAlignment.RIGHT);
    }
    super.onBrowserEvent(event);
  }

}
